# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 师生关系模型
管理学员和教练之间的双选关系
"""

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

from app import db


class StudentCoachRelation(db.Model):
    """
    师生关系模型
    管理学员选择教练的申请、审核和关系状态
    """
    __tablename__ = 'student_coach_relations'

    # 基础字段
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    student_id = db.Column(db.BigInteger, db.ForeignKey('users.id'),
                          nullable=False, comment='学员ID')
    coach_id = db.Column(db.BigInteger, db.ForeignKey('users.id'),
                        nullable=False, comment='教练ID')

    # 状态和备注（严格按照数据库结构）
    status = db.Column(db.Enum('pending', 'approved', 'rejected'),
                      nullable=False, default='pending', comment='关系状态')
    apply_note = db.Column(db.String(255), nullable=True, comment='申请备注')
    response_note = db.Column(db.String(255), nullable=True, comment='回复备注')

    # 时间记录（严格按照数据库结构）
    applied_at = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='申请时间')
    responded_at = db.Column(db.DateTime, nullable=True, comment='回复时间')

    # 关联关系由User模型通过backref创建

    # 唯一约束
    __table_args__ = (
        db.UniqueConstraint('student_id', 'coach_id', name='unq_relation_student_coach'),
    )

    def __init__(self, **kwargs):
        super(StudentCoachRelation, self).__init__(**kwargs)

    def approve(self, response_note=None):
        """批准申请"""
        self.status = 'approved'
        self.responded_at = datetime.now()
        if response_note:
            self.response_note = response_note

    def reject(self, response_note=None):
        """拒绝申请"""
        self.status = 'rejected'
        self.responded_at = datetime.now()
        if response_note:
            self.response_note = response_note

    def is_approved(self):
        """是否已批准"""
        return self.status == 'approved'

    def is_pending(self):
        """是否待审核"""
        return self.status == 'pending'

    def is_rejected(self):
        """是否已拒绝"""
        return self.status == 'rejected'

    def get_status_display(self):
        """获取状态显示文本"""
        status_map = {
            'pending': '待审核',
            'approved': '已通过',
            'rejected': '已拒绝'
        }
        return status_map.get(self.status, self.status)

    def can_be_modified(self):
        """是否可以修改"""
        return self.status == 'pending'

    def get_duration_days(self):
        """获取关系持续天数"""
        if not self.is_approved():
            return 0
        end_date = datetime.now()
        start_date = self.responded_at or self.applied_at
        return (end_date - start_date).days

    @staticmethod
    def get_relation(student_id, coach_id):
        """获取指定师生关系"""
        return StudentCoachRelation.query.filter_by(
            student_id=student_id,
            coach_id=coach_id
        ).first()

    @staticmethod
    def exists_relation(student_id, coach_id):
        """检查师生关系是否存在"""
        relation = StudentCoachRelation.get_relation(student_id, coach_id)
        return relation is not None

    @staticmethod
    def has_approved_relation(student_id, coach_id):
        """检查是否存在已批准的师生关系"""
        relation = StudentCoachRelation.get_relation(student_id, coach_id)
        return relation and relation.is_approved()

    @staticmethod
    def get_student_coaches(student_id, status=None):
        """获取学员的教练列表"""
        query = StudentCoachRelation.query.filter_by(student_id=student_id)
        if status:
            query = query.filter_by(status=status)
        return query.all()

    @staticmethod
    def get_coach_students(coach_id, status=None):
        """获取教练的学员列表"""
        query = StudentCoachRelation.query.filter_by(coach_id=coach_id)
        if status:
            query = query.filter_by(status=status)
        return query.all()

    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'student_id': self.student_id,
            'coach_id': self.coach_id,
            'status': self.status,
            'status_display': self.get_status_display(),
            'apply_note': self.apply_note,
            'response_note': self.response_note,
            'applied_at': self.applied_at.isoformat() if self.applied_at else None,
            'responded_at': self.responded_at.isoformat() if self.responded_at else None,
            'student_name': self.student.real_name if self.student else None,
            'coach_name': self.coach.real_name if self.coach else None,
            'duration_days': self.get_duration_days()
        }

    def __repr__(self):
        student_name = self.student.real_name if self.student else f'Student({self.student_id})'
        coach_name = self.coach.real_name if self.coach else f'Coach({self.coach_id})'
        return f'<Relation {student_name} -> {coach_name} ({self.status})>'